<template>
  <div>
    <el-form :model="form" label-width="auto" inline>
      <el-form-item>
        <el-select v-model="select" placeholder="Select" style="width: 115px">
          <el-option label="采购时间" value="2" />
          <el-option label="提交时间" value="3" />
        </el-select>
        <el-date-picker v-model="form.times" type="datetimerange" start-placeholder="开始时间" value-format="x"
          end-placeholder="结束时间" time-format="A hh:mm:ss" />
      </el-form-item>
      <el-form-item label="采购平台:">
        <el-select v-model="form.purchasePlatformId">
          <el-option label="全部" :value="0"></el-option>
          <el-option :label="item.value" :value="item.key"
            v-for="item in store.productPurchaseProcessCreatePurchaseProcessDicArr" :key="item.key"
            @click="getSon(item)" />
        </el-select>
      </el-form-item>
      <el-form-item label="采购账号:">
        <el-select v-model="form.purchaseCustomerName">
          <el-option :label="item.value" :value="item.name" v-for="item in sonSelect" :key="item.key" />
        </el-select>
      </el-form-item>
      <el-form-item label="采购订单号:">
        <el-input v-model="form.productPurchaseOrderCode" clearable />
      </el-form-item>
      <el-form-item label="上家物流单号:">
        <el-input v-model="form.trackingNumbers" clearable />
      </el-form-item>
      <el-form-item label="质检结果:">
        <el-select v-model="form.processQualityStatus">
          <el-option label="全部" :value="0" />
          <el-option label="部分未通过" :value="2" />
          <el-option label="未通过" :value="3" />
          <el-option label="通过" :value="1" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="onSubmit">搜索</el-button>
      </el-form-item>
    </el-form>
  </div>
  <div class="table">
    <el-table ref="multipleTableRef" :data="tableData" style="width: 100%" @selection-change="handleSelectionChange"
      border>
      <!-- <el-table-column type="selection" width="55" /> -->
      <el-table-column label="采购平台">
        <template #default="scope">{{ scope.row.purchasePlatformName }}</template>
      </el-table-column>
      <el-table-column label="采购账号" width="180">
        <template #default="scope">{{ scope.row.purchaseCustomerName }}</template>
      </el-table-column>
      <el-table-column label="采购时间" width="180">
        <template #default="scope">{{ scope.row.submitTime }}</template>
      </el-table-column>
      <el-table-column label="采购订单号" width="180">
        <template #default="scope">{{ scope.row.productPurchaseOrderCode }}</template>
      </el-table-column>
      <el-table-column label="商品信息" width="180">
        <template #default="scope">{{ scope.row.shopGoodSkuId }}</template>
      </el-table-column>
      <el-table-column label="采购数量">
        <template #default="scope">{{ scope.row.purchaseNum }}</template>
      </el-table-column>
      <el-table-column label="上家订单状态">
        <template #default="scope">{{ scope.row.processOrderStatus == 0 ? '待发货' :
          scope.row.processOrderStatus == 1 ? '已发货' : scope.row.processOrderStatus == 1 ? '待签收' : '' }}</template>
      </el-table-column>
      <el-table-column label="上家物流单号">
        <template #default="scope">{{ scope.row.trackingNumbers }}</template>
      </el-table-column>
      <el-table-column label="质检结果">
        <template #default="scope">{{ scope.row.processQualityStatus == 0 ? '未质检' : scope.row.processQualityStatus == 1
          ? '质检通过' :
          scope.row.processQualityStatus == 2 ? '部分通过' : scope.row.processQualityStatus == 3 ? '不通过' : '' }}</template>
      </el-table-column>
      <el-table-column label="未通过原因">
        <template #default="scope">{{ scope.row.processQualityRefuseReason }}</template>
      </el-table-column>
      <el-table-column label="未通过数量">
        <template #default="scope">{{ scope.row.processQualityRefuseNum }}</template>
      </el-table-column>
      <el-table-column label="操作" width="180">
        <template #default="scope">
          <el-button link type="primary" size="small" @click.prevent="returnON(scope.row)">
            取消入库
          </el-button>
          <el-button link type="primary" size="small" @click.prevent="disposeOrder(scope.row)"
            v-if="scope.row.processQualityStatus !== 1">
            去处理
          </el-button>
          <el-button v-else link type="primary" size="small" @click.prevent="printProductPurchaseStorageBtn(scope.row)">
            打印入库单
          </el-button>
        </template>
      </el-table-column>
    </el-table>
  </div>

  <div class="page">
    <el-pagination v-model:current-page="currentPage4" v-model:page-size="pageSize4" :page-sizes="[10, 50, 100]"
      layout="total, sizes, prev, pager, next, jumper" :total="total" @size-change="handleSizeChange"
      @current-change="handleCurrentChange" />
  </div>
  <!-- 处理 -->
  <el-dialog v-model="qualityTestingDialogVisible" width="700">
    <span>
      <h3>质检未通过部分:</h3>
      <p><span>采购订单号：{{ qualityTestingFormContent.productPurchaseOrderCode
          }}</span><span>采购账号：{{ qualityTestingFormContent.purchaseCustomerName }}</span>
        <span>不通过的数量：<span style="color: red;">{{ qualityTestingFormContent.processQualityRefuseNum }}</span></span>
      </p>
      <p>不通过的原因：{{ qualityTestingFormContent.processQualityRefuseReason }}</p>
      <p>请先选择处理结果： <label>
          <input type="radio" :value="1" v-model="qualityTestingForm.processQualityStatus" @click="claerContent">
          退货退款
        </label>
        <label>
          <input type="radio" :value="2" v-model="qualityTestingForm.processQualityStatus" @click="claerContent">
          仅退款
        </label>
        <label>
          <input type="radio" :value="3" v-model="qualityTestingForm.processQualityStatus"
            @click="openQualityTestingSon">
          小额打款
        </label>
      </p>
      <div v-if="qualityTestingForm.processQualityStatus == 1">
        <p>
          <label>
            <input type="radio" :value="1" v-model="qualityTestingForm.OneProcessQualityStatus">
            不通过的退回
          </label>
          <label>
            <input type="radio" :value="2" v-model="qualityTestingForm.OneProcessQualityStatus">
            全部退回
          </label>
        </p>
        <p>退回数量： <input v-model="qualityTestingForm.processQualityBouncedNum"></p>
      </div>
      <div v-if="qualityTestingForm.processQualityStatus == 2">
        <p>
          <label>
            <input type="radio" :value="3" v-model="qualityTestingForm.OneProcessQualityStatus">
            部分退款
          </label>
          <label>
            <input type="radio" :value="4" v-model="qualityTestingForm.OneProcessQualityStatus">
            全额退款
          </label>
        </p>
        <p>退款金额： <input v-model="qualityTestingForm.processQualityBouncedAmount"></p>
      </div>
      <p v-if="qualityTestingForm.processQualityStatus == 3">打款金额： <input
          v-model="qualityTestingForm.processQualityBouncedAmount"></p>
      <div>
        <h3>质检通过部分:</h3>
        <div style="display: flex">
          <label>
            <input type="radio" :value="0" v-model="dialogVisiblesForm">
            自动分配库区库位：
          </label>
          <label>
            <input type="radio" :value="1" v-model="dialogVisiblesForm">
            手动分配库区库位
          </label>
        </div>
        <div v-if="dialogVisiblesForm === 1">
          库区：<el-select v-model="warehouseKqu" filterable>
            <el-option :label="item.areaName" :value="item.areaId" v-for="item in dialogVisiblesHOuse"
              @click="pushWare(item.warehouseLocationAllWithNameVOList)" :key="item.key" />
          </el-select>
          <div ref="NUMDom" v-for="(item, index) in numsKey   " :key='index'>
            库位号：<el-select v-model="warehouseLocationSelectId[index]" filterable>
              <el-option :label="item.name" :value="item.id" v-for="item in warehouseKwSelect" :key="item.key" />
            </el-select>
            数量:<el-input v-model="numsKeyObj[index]" type="number" style="width: 200px;" /><el-icon
              @click="upNum(NUMDom)">
              <Plus />
            </el-icon><el-icon @click="downNum" style="margin-left: 20px;">
              <Minus />
            </el-icon>
          </div>
        </div>
        <p><span>采购订单号：{{ qualityTestingFormContent.productPurchaseOrderCode
            }}</span><span>采购账号：{{ qualityTestingFormContent.purchaseCustomerName }}</span>
          <span>通过的数量：<span style="color: red;">{{
            qualityTestingFormContent.purchaseNum - qualityTestingFormContent.processQualityRefuseNum }}</span></span>
        </p>
      </div>
    </span>
    <template #footer>
      <div class="dialog-footer">
        <el-button type="primary" @click="onSubmitQualityTesting">
          保存并生成入库单
        </el-button>
      </div>
    </template>
  </el-dialog>

</template>

<script setup>
import { ref, onBeforeMount, onMounted, onBeforeUnmount } from 'vue'
import { productPurchaseProceslist, printProductPurchaseStorage, cancelProductPurchaseStorageStatus, productPurchaseProcesswarehouseLocationCanUseList, printProductWithLocationAndRefuseHandle } from '@/api/index'
import { useAlertsStore } from '@/store/index'
import { ElMessage } from 'element-plus'
const store = useAlertsStore()
// do not use same name with ref
const form = ref({
  createTimeStart: '',
  createTimeEnd: '',
  submitTimeStart: '',
  submitTimeEnd: '',
  purchasePlatformId: 0,
  purchaseCustomerName: '',
  productPurchaseOrderCode: '',
  processQualityStatus: 0,
  trackingNumbers: '',
  pageSize: 10,
  pageNum: 1
})
const tableData = ref([])
onBeforeMount(() => {
  store.productPurchaseProcessCreatePurchaseProcessDicBtn()
  doConnect()
})
onMounted(() => {
  doConnect()
})
const onSubmit = () => {
  getList()
  console.log('submit!')
}
const times = ref('')
const select = ref('2')
const getList = () => {
  if (times.value) {
    if (select.value === '2') {
      form.value.createTimeStart = times.value[0]
      form.value.createTimeEnd = times.value[1]
    } else if (select.value === '3') {
      form.value.submitTimeStart = times.value[0]
      form.value.submitTimeEnd = times.value[1]
    }
  } else {
    form.value.createTimeStart = ''
    form.value.createTimeEnd = ''
    form.value.submitTimeStart = ''
    form.value.submitTimeEnd = ''
  }
  productPurchaseProceslist(form.value).then(res => {
    const { data: { data } } = res
    total.value = data.total
    tableData.value = data.list
  })
}
// 分页
const currentPage4 = ref(1)
const pageSize4 = ref(10)
const total = ref(0)
const handleSizeChange = (val) => {
  console.log(`${val} items per page`)
  form.value.pageSize = val
  getList()
}
const handleCurrentChange = (val) => {
  console.log(`current page: ${val}`)
  form.value.pageNum = val
  getList()
}

// table
const multipleSelection = ref([])
const handleSelectionChange = (val) => {
  multipleSelection.value = val
}

// 处理
const qualityTestingDialogVisible = ref(false)
const qualityTestingFormContent = ref({})
const dialogVisiblesHOuse = ref([])
// const qualityTestingContentDialogVisible = ref(false)
const disposeOrder = (row) => {
  productPurchaseProcesswarehouseLocationCanUseList(row.id, {
    areaName: ''
  }).then(res => {
    const { data: { data } } = res
    dialogVisiblesHOuse.value = data
  })
  qualityTestingDialogVisible.value = true
  qualityTestingFormContent.value = row
  qualityTestingFormid.value = row.id
}
const qualityTestingFormid = ref('')
const qualityTestingForm = ref({ processQualityBouncedNum: '0', processQualityBouncedAmount: '0.00' })
const onSubmitQualityTesting = () => {
  if (dialogVisiblesForm.value === 0) {
    printProductWithLocationAndRefuseHandle(qualityTestingFormid.value, {
      type: dialogVisiblesForm.value,
      productPurchaseStorageWarehouseLocationListParamList: [],
      productPurchaseProcessRefuseHandleParam: {
        processQualityRefuseHandle: qualityTestingForm.value.OneProcessQualityStatus,
        processQualityBouncedNum: qualityTestingForm.value.processQualityBouncedNum,
        processQualityBouncedAmount: qualityTestingForm.value.processQualityBouncedAmount
      }
    }).then(res => {
      ElMessage.success('操作成功')
      qualityTestingDialogVisible.value = false
      getList()
      printProductPurchaseStorageBtn(qualityTestingFormContent.value)
    })
  }
  if (dialogVisiblesForm.value === 1) {
    const a = []
    for (let index = 0; index < numsKey.value; index++) {
      console.log('11111', index)
      console.log(numsKeyObj.value[index])
      a.push({
        warehouseLocationId: warehouseLocationSelectId[index],
        cargoMargin: numsKeyObj.value[index]
      })
      console.log('a')
      console.log(a)
    }
    printProductWithLocationAndRefuseHandle(qualityTestingFormid.value, {
      type: dialogVisiblesForm.value,
      productPurchaseStorageWarehouseLocationListParamList: a,
      productPurchaseProcessRefuseHandleParam: {
        processQualityRefuseHandle: qualityTestingForm.value.OneProcessQualityStatus,
        processQualityBouncedNum: qualityTestingForm.value.processQualityBouncedNum,
        processQualityBouncedAmount: qualityTestingForm.value.processQualityBouncedAmount
      }
    }).then(res => {
      ElMessage.success('操作成功')
      qualityTestingDialogVisible.value = false
      getList()
      printProductPurchaseStorageBtn(qualityTestingFormContent.value)
    })
  }
}
const sonSelect = ref([])
const getSon = (item) => {
  sonSelect.value = item.purchaseCustomerDics
  console.log(sonSelect.value)
}
const openQualityTestingSon = () => {
  qualityTestingForm.value.OneProcessQualityStatus = 5
  qualityTestingForm.value.processQualityBouncedAmount = ''
  qualityTestingForm.value.processQualityBouncedNum = ''
}
const claerContent = () => {
  qualityTestingForm.value.processQualityBouncedAmount = ''
  qualityTestingForm.value.processQualityBouncedNum = ''
}

const printProductPurchaseStorageBtn = (row) => {
  printProductPurchaseStorage(row.id).then(res => {
    const { data: { data } } = res
    const a = []
    JSON.parse(data.storageWarehouseLocation).warehouseLocationData.forEach(element => {
      const aa = {}
      aa.areaShop = JSON.parse(data.storageWarehouseArea).warehouseAreaData[0].name
      aa.storagelocation = element.name
      aa.num = element.needSave
      aa.skuInfos = element.skuInfo
      aa.batchNum = data.inboundBatchesCode
      a.push(aa)
    })
    // ElMessage.success('操作成功')
    if (localStorage.getItem('PrinterSetListRK')) {
      const lists = JSON.parse(localStorage.getItem('PrinterSetListRK'))
      console.log(lists[0].PrinterList)
      console.log(a)
      console.log(data.pdaCode)
      console.log(data.inboundBatchesCode)
      const val = {
        cmd: 'print',
        requestID: '123458976',
        version: '1.0',
        task: {
          taskID: (new Date().getTime() + ''),
          preview: false,
          printer: lists[0].PrinterList,
          notifyMode: 'allInOne',
          previewType: 'pdf',
          documents: [{
            documentID: '0123456789',
            contents: [{
              data: {
                width: '210',
                height: '297',
                padding: '2',
                fontSize: '8',
                left: '2',
                skuInfo: a,
                padcode: data.pdaCode,
                // batchNum: data.inboundBatchesCode,
                barcodeHeight: '33'
              },
              templateURL: 'http://yitaoweb.sc.kuaidi600.com/moban/a4.xml'
            }]
          }]
        }
      }
      store.socket.send(JSON.stringify(val))
    } else {
      ElMessage.error('先设置打印机')
    }
    getList()
  })
}
const doConnect = () => {
  console.log('d打开了不')
  store.socket = new WebSocket('ws://localhost:13528')
  // 打开Socket
  store.socket.onopen = function (event) {
    // 监听消息
    store.socket.onmessage = function (event) {
      // localStorage.setItem('printerproperties', event.data)
    }
    // 监听Socket的关闭
    store.socket.onclose = function (event) {
      // console.log('Client notified socket has closed', event)
    }
  }
}
// 销毁
onBeforeUnmount(() => {
  console.log('销毁')
  store.destroyed()
})
const NUMDom = ref('')
const numsKey = ref(1)
const warehouseLocationSelectId = ref({})
const numsKeyObj = ref({})
const upNum = (NUMDom) => {
  numsKey.value++
}
const downNum = () => {
  numsKey.value--
}
const warehouseKqu = ref('')
const warehouseKwSelect = ref([])
const dialogVisiblesForm = ref(0)
const pushWare = (row) => {
  warehouseKwSelect.value = row
}
const returnON = (row) => {
  cancelProductPurchaseStorageStatus(row.id).then(res => {
    ElMessage.success('操作成功')
    getList()
  })
}
</script>

<style lang='less' scoped></style>
